import { MpUser } from '@/types'

interface Header {
	alg: string
	typ: string
}

interface Payload {
	token: string
	createdAt: number
	endAt: number
}

interface Jwt {
	jwtToken: string
	header: Header
	payload: Payload
	signature: string
}

export default {
	namespaced: true, // 开启命名空间
	state: {
		jwt: <Jwt>{
			jwtToken: '',
			header: {
				alg: '',
				typ: ''
			},
			payload: {
				token: '',
				createdAt: 0,
				endAt: 0
			},
			signature: ''
		},
		encryptedMpUserKey: '',
		mpUser: <MpUser>{
			id: 0,
			nickname: '',
			avatar: '',
			mobile: '',
			gender: 0,
			status: 1,
			createdAt: 0,
			updatedAt: 0
		}
	},
	getters: {
		getJwt: (state) => {
			return state.jwt
		},
		getEncryptedMpUserKey: (state) => {
			return state.encryptedMpUserKey
		},
		getMpUser: (state) => {
			return state.mpUser
		}
	},
	mutations: {
		updateJwtToken(state, newJwtToken) {
			console.log('updatedJwt:', newJwtToken)
			state.jwt.jwtToken = newJwtToken
			if (state.jwt.jwtToken) {
				const jwtArr = state.jwt.jwtToken.split('.')
				const headerStrbase64 = jwtArr[0]
				const headerStr = atob(headerStrbase64)
				state.jwt.header = <Header>JSON.parse(headerStr)
				const payloadStrbase64 = jwtArr[1]
				const payloadStr = atob(payloadStrbase64)
				state.jwt.payload = JSON.parse(payloadStr)
				state.jwt.signature = jwtArr[2]
			}
		},
		updateEncryptedMpUserKey(state, newEncryptedMpUserKey) {
			state.encryptedMpUserKey = newEncryptedMpUserKey
		},
		updateMpUser(state, newMpUser) {
			state.mpUser = Object.assign(state.mpUser, newMpUser)
			console.log('updatedMpUser:', newMpUser)
		}
	}
}
